<template>
    <el-form label-width="80px">
        <el-form-item label="SPU名称">
            <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
        </el-form-item>

        <el-form-item label="品牌">
            <el-select placeholder="请选择" v-model="spuInfo.tmId">
                <el-option v-for="item in tmList" :key="item.id" :value="item.id" :label="item.tmName"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="SPU描述">
            <el-input type="textarea" v-model="spuInfo.description" rows="6" placeholder="SPU描述"></el-input>
        </el-form-item>

        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="spuImageList" :action="`${baseUrl}/admin/product/upload`"
                list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </el-form-item>

        <el-form-item label="销售属性">
            <el-select :placeholder="`还有${unUseSaleAttrList.length}未选择`" v-model="tempSaleAttr">
                <el-option v-for="item in unUseSaleAttrList" :key="item.id" :value="`${item.id}:${item.name}`"
                    :label="item.name"></el-option>
            </el-select>
            <el-button :disabled="!tempSaleAttr" type="primary" @click="addSaleAttr">添加销售属性</el-button>
        </el-form-item>

        <el-form-item>
            <el-table :data="spuSaleAttrList" border stripe>
                <el-table-column type="index" width="80" align="center" label="序号" />
                <el-table-column label="属性名" prop="saleAttrName" />
                <el-table-column label="属性值名称列表">
                    <template v-slot="{ row }">
                        <el-tag v-for="(tag, index) in row.spuSaleAttrValueList" :key="tag.id" class="mx-1" closable
                            :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index, 1)">
                            {{ tag.saleAttrValueName }}
                        </el-tag>
                        <input v-if="row.isEdit" @blur="changeToLook(row)" ref="inputEle" v-model="row.inputValue" />
                        <el-button v-else @click="changeToEdit(row)" class="button-new-tag ml-1" size="small">添加属性值
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{ $index }">
                        <el-button type="danger" icon="ele-Delete" @click="spuSaleAttrList.splice($index, 1)">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>

        <el-form-item label="">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button @click="emit('setState', 0)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import {requestUpdateSpuInfo , requestSaveSpuInfo ,  requestBaseSaleAttrList, requestSpuImageList, requestSpuSaleAttrList, type BaseSaleAttrListType, type SpuImageListType, type SpuSaleAttrListType, type supInfoType } from '@/api/spu';
import { ElMessage } from 'element-plus'

export default defineComponent({
    name: "SpuFrom",
});
</script>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import type { TmListType } from "@/api/tradmark"
import { requestAllTmList } from "@/api/tradmark"
const baseUrl = import.meta.env.VITE_API_URL;


//1.接收父组件的自定义事件点击取消调用，显示不同的子组件
const emit = defineEmits<{
    (event: 'setState', state: number, row?: supInfoType): void
}>()

//2.接收spuInfo等下发送修改或添加请求要用
const props = defineProps<{
    spuInfo: supInfoType
}>()

//定义当前组件初始化请求需要的数据
const tmList = ref<TmListType[]>()
const allSaleAttrList = ref<BaseSaleAttrListType>([])
const spuImageList = ref<SpuImageListType>([])
const spuSaleAttrList = ref<SpuSaleAttrListType>([])

//判断是新增还是修改，新增发送2个请求(1.品牌列表，2.所有销售属性列表)
//修改发送4个请求(1.品牌列表，2.所有销售属性列表，3.根据supId请求图片列表，4.根据supId请求销售属性列表，)
const getUseData = async () => {
    try {
        if (!props.spuInfo.id) {
            //没有id代表添加，发送2个请求
            const result1 = await requestAllTmList()
            tmList.value = result1
            const result2 = await requestBaseSaleAttrList()
            allSaleAttrList.value = result2
        } else {
            //有id代表修改，发送4个请求
            const promise1 = requestAllTmList()
            const promise2 = requestBaseSaleAttrList()
            const promise3 = requestSpuImageList(props.spuInfo.id)
            const promise4 = requestSpuSaleAttrList(props.spuInfo.id)
            //发送请求
            const result = await Promise.all([promise1, promise2, promise3, promise4])
            //把请求回的数据保存到响应式数据中
            tmList.value = result[0]
            allSaleAttrList.value = result[1]
            spuImageList.value = result[2]
            //修改图片列表数据
            spuImageList.value.forEach((item) => {
                item.name = item.imgName
                item.url = item.imgUrl
            })
            spuSaleAttrList.value = result[3]
            spuSaleAttrList.value.forEach((item) => {
                //给销售属性列表添加数据保存状态
                item.isEdit = false
                //给销售属性添加属性保存输入框的值
                item.inputValue = ""
            })
        }
    } catch (error) {
        ElMessage.error("初始化请求数据失败!")
    }
}
//3.初始化请求需要的数据
onMounted(() => {
    getUseData()
})

//4.计算出没使用的销售属性列表
const unUseSaleAttrList = computed(() => {
    return allSaleAttrList.value.filter((item) => {
        return !spuSaleAttrList.value.some((item1) => {
            return item.name === item1.saleAttrName
        })
    })
})

//定义数据接收用户临时点击的销售属性
const tempSaleAttr = ref("")
//5.点击添加销售属性的回调
const addSaleAttr = () => {
    const [baseSaleAttrId, saleAttrName] = tempSaleAttr.value.split(":")
    //创建一条销售属性数据
    const newSaleAttr = {
        baseSaleAttrId: +baseSaleAttrId,
        saleAttrName: saleAttrName,
        spuSaleAttrValueList: []
    }
    //把新销售属性插入spu销售属性列表
    spuSaleAttrList.value.push(newSaleAttr)

    //清空临时数据
    tempSaleAttr.value = ""
}


//拿到输入框元素
const inputEle = ref<HTMLInputElement>()
//6.点击button切换状态
const changeToEdit = (row: SpuSaleAttrItemType) => {
    //切换状态
    row.isEdit = true
    //获取焦点
    nextTick(() => {
        inputEle.value.focus()
    })
}

//7.失去焦点的事件
const changeToLook = (row: SpuSaleAttrItemType) => {
    //拿到失去焦点之前的输入框值
    const oldInputValue = row.inputValue

    //判断为空
    if (!oldInputValue) {
        //切换状态
        row.isEdit = false
        ElMessage.error("输入内容为空!")
        return;
    }

    //判断输入重复
    const isRepect = row.spuSaleAttrValueList.some((item) => {
        return item.saleAttrValueName === oldInputValue
    })
    if (isRepect) {
        //切换状态
        row.isEdit = false
        //清空输入框
        row.inputValue = ""
        ElMessage.error("输入内容重复!")
        return;
    }

    //输入内容正常，创建要添加的属性值数据
    const newAtteValue = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrName: row.saleAttrName,
        saleAttrValueName: oldInputValue,
    }
    //插入属性值列表
    row.spuSaleAttrValueList.push(newAtteValue)

    //清空输入框，切换状态
    row.isEdit = false
    row.inputValue = ""

}

//8.点击保存的回调
const save = async () => {
    //整理图片列表数据
    const newSpuImageList = spuImageList.value.map((item) => {
        if (item.response) {
            return {
                imgUrl: item.response.data as string,
                imgName: item.name as string
            }
        } else {
            return {
                imgUrl: item.url as string,
                imgName: item.name as string
            }
        }
    })

    //整理销售属性列表数据
    spuSaleAttrList.value.forEach((item) => {
        delete item.isEdit
        delete item.inputValue
    })

    //赋值
    props.spuInfo.spuImageList = newSpuImageList
    props.spuInfo.spuSaleAttrList = spuSaleAttrList.value

    //请求
    try {
        if (props.spuInfo.id) {
            await requestUpdateSpuInfo(props.spuInfo)
        } else {
            await requestSaveSpuInfo(props.spuInfo)
        }

        //成功提示
        ElMessage.success(props.spuInfo.id ? '修改spu成功!' : '添加spu成功!')

        //不管是新增还是修改都回到首页
        emit("setState", 0);

    } catch (error) {
        //失败提示
        ElMessage.error(props.spuInfo.id ? '修改spu失败!' : '添加spu失败!')
    }

}


//照片墙逻辑
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}



</script>